﻿package net.wangit.dev.table;

import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.action.Unit2ExcelAction;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;


public class Table2ExcelAction extends Unit2ExcelAction {

	public Table2ExcelAction() {
	}

	protected void config(ActionContext ac) throws Exception {
		super.config(ac);
		String domain = ConsoleDomainUtil.getDomain(ac);
		String tableName = ActionContextHelper.getRequest2Session(ac,
				"tablename", "net.wangit.dev.table.TableUI.tablename", null);
		DB db = DBHelper.getDomainDB(domain);
		data = db.query("select * from COLUMN where t=? order by o", tableName,
				2);
		uc.setData(data);
		elements.remove(uc.getElement("v"));
		elements.remove(uc.getElement("o"));
		uc.getElement("pk").setName("主键");
		uc.getElement("nn").setName("不可空");
		for (int i = 0; i < data.size(); i++) {
			Row row = data.getRow(i);
			if ("0".equals(row.get("pk")))
				data.put(i, "pk", "");
			if ("0".equals(row.get("nn")))
				data.put(i, "nn", "");
		}

	}

	protected String getFileName(ActionContext ac) {
		return ActionContextHelper.getRequest2Session(ac, "tablename",
				"net.wangit.dev.table.TableUI.tablename", null);
	}

	protected void resetSheet(ActionContext ac, HSSFWorkbook wb, HSSFSheet sheet) {
		String tableName = ActionContextHelper.getRequest2Session(ac,
				"tablename", "net.wangit.dev.table.TableUI.tablename", null);
		HSSFRow row = sheet.getRow(0);
		row.setHeightInPoints(30F);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue(new HSSFRichTextString(tableName));
		cell.setCellStyle(createTitleStyle(wb));
		sheet
				.addMergedRegion(new CellRangeAddress(0, 0, 0,
						elements.size() - 1));
	}

	private HSSFCellStyle createTitleStyle(HSSFWorkbook wb) {
		HSSFFont font = wb.createFont();
		font.setBoldweight((short) 700);
		font.setFontHeightInPoints((short) 11);
		HSSFCellStyle style = wb.createCellStyle();
		style.setFont(font);
		style.setAlignment((short) 2);
		style.setVerticalAlignment((short) 1);
		return style;
	}
}
